<?php
/**
 * File: WebController.php.
 * User: Yan<me@xiaoyan.me>
 * DateTime: 2017-12-20 9:08
 */

namespace App\Core;


class WebController
{
    public function index()
    {
        return get_class($this) . '@index';
    }

    /**
     * @var Request
     */
    private $request;

    public function __intEnv(Request $request)
    {
        $this->request = $request;
    }

    private $vars = [];

    protected function assign($k, $v)
    {
        $this->vars[$k] = $v;
    }

    /**
     * @param $viewName
     * @param array $dataArray
     * @param bool $show_header
     */
    protected function render($viewName, $dataArray = [], $show_header = true)
    {
        $dataArray = array_merge($this->vars, $dataArray);
        extract($dataArray);
        $user = $this->request->user;
        if ($show_header) include view('header');
        include view($viewName);
        if ($show_header) include view('footer');
    }

    protected function warn($message, $sub_message = '')
    {
        include view('message', 'warn');
        exit;
    }

    protected function info($message, $sub_message = '')
    {
        include view('message', 'info');
        exit;
    }

    protected function message($message, $status = 'info', $sub_message = '')
    {
        include view('message');
        exit;
    }

    protected function check_etag($tag_key, $exp_time = 7200)
    {
        $etag = strlen($tag_key) >= 15 ? $tag_key : md5($tag_key);
        $etag = substr($etag, 0, 10) . '-' . substr($etag, 10, 5);

        header('Cache-Control: max-age=' . $exp_time . ',must-revalidate');
        header('Last-Modified: ' . gmdate('D,d M Y H:i:s') . ' GMT');
        header('Expires: ' . gmdate('D,d M Y H:i:s', time() + $exp_time) . ' GMT');

        $req_e_tag = isset($_SERVER['HTTP_IF_NONE_MATCH'])
            ? str_replace(['W/', '-gzip'], '', $_SERVER['HTTP_IF_NONE_MATCH']) : null;
        if ($req_e_tag == '"' . $etag . '"') {
            header('ETag: "' . $etag . '"', true, 304);
            exit('file not modify!');
        } else {
            header('ETag: "' . $etag . '"');
        }
    }
}